package com.sophie.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.sophie.entity.Follow;
import com.sophie.entity.User;
import com.sophie.service.IFollowService;
import com.sophie.service.IUserService;
import com.sophie.service.IZoneService;
import com.sophie.service.impl.FollowServiceImpl;
import com.sophie.service.impl.UserServiceImpl;
import com.sophie.service.impl.ZoneServiceImpl;
import com.sophie.util.*;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;

@WebServlet(name = "UserServlet", value = "/UserServlet")
@MultipartConfig
public class UserServlet extends BaseServlet {
    IUserService userService = new UserServiceImpl();
    IZoneService zoneService= new ZoneServiceImpl();
    IFollowService followService = new FollowServiceImpl();

    //UserServlet?method=register
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("调用----->注册");
        //接受参数
        String name = request.getParameter("name");
        String password = request.getParameter("password");

        System.out.println(name + "---->" + password);
        //
        User user = new User(null, name, password, null, null, null, null, null, null, null, null);
        ResultVO resultVO = userService.register(user);
        if (resultVO.getCode() == 0) {
            HttpSession session = request.getSession();

            session.setAttribute("id", resultVO.getData());

            response.sendRedirect("login.jsp");
        } else {
            request.setAttribute("resultVO", resultVO);
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }

    }

    //UserServlet?method=login
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------------>登录");
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        //调用service
        ResultVO resultVO = userService.login(name, password);
        if (resultVO.getCode() == 0) {
            HttpSession session = request.getSession();
            session.setAttribute("user", resultVO.getData());
//            System.out.println("------->" + resultVO.getData());
            session.setAttribute("loginUser", resultVO.getData());
            //使用cookie记住密码
            String rememberMe = request.getParameter("rememberMe");
//            System.out.println("---------->rememberMe=" + rememberMe);
            if ("on".equals(rememberMe)) {
                //勾选后
                CookieUtil.setCookie("userInfo", name + ":" + password, request, response);
            } else {
                //没勾选
                CookieUtil.removeCookie("userInfo", request, response);
            }
            response.sendRedirect("UserServlet?method=mainPage");
        } else {
            System.out.println("怎么回事？");
            request.setAttribute("errTip", resultVO.getMsg());
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }

    //UserServlet?method=mainPage
    protected void mainPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("调用----->这里是主页面");
        HttpSession session = request.getSession();
        ResultVO resultVO = userService.getUserList();
        User user = (User) session.getAttribute("user");

        request.setAttribute("resultVO", resultVO);
        request.getRequestDispatcher("main.jsp").forward(request, response);

    }

    //UserServlet?method=toUpdatePage
    protected void toUpdatePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("调用----->跳转编辑资料页面");
        User user = (User) request.getSession().getAttribute("user");

        ResultVO resultVO = userService.getUserById(user.getId());
        if (resultVO.getCode() == 0) {
            System.out.println("result----->"+resultVO.getData());
            //获取用户所以动态
            ResultVO myZones= zoneService.getZonesByUserId(user.getId());
            request.setAttribute("myZones", myZones.getData());
            request.setAttribute("resultVO", resultVO);
            request.getRequestDispatcher("individual.jsp").forward(request, response);
        }else{
            request.setAttribute("errTip", resultVO.getMsg());
        }

    }
    //UserServlet?method=editUser
    protected void editUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("调用----->编辑用户资料");
        //
        String id = request.getParameter("id");

        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String gender = request.getParameter("gender");
        String birthday = request.getParameter("birthday");
        String education = request.getParameter("education");
        String address = request.getParameter("address");
        String hobby = request.getParameter("hobby");
        String likeType = request.getParameter("likeType");
        String avatar = request.getParameter("user-avatar");
        String motto = request.getParameter("motto");

        //头像/图片(文件上传，获取附件)
        //使用这个方法的前提：@MultipartConfig
        Part part = request.getPart("avatar");
        if (!"".equals(part.getSubmittedFileName())){
            //设置电脑磁盘存放图片的路径
//            String dirPath="D:/java/imgs"+request.getContextPath();
//            System.out.println("路径："+dirPath);
//            String fileName = FileUploadUtil.uploadImage(part, request);
//            QCloudUtil.upload(fileName,dirPath+"/"+fileName);
            avatar=FileUploadUtil.uploadImage(part,request);

        }

        System.out.println(id+"-"+name+"-"+password+"-"+gender+"-"+birthday);
        System.out.println(education+"-"+address+"-"+hobby+"-"+likeType);
        System.out.println(motto);
        System.out.println("avatar----->"+avatar);
        User user = new User(Integer.parseInt(id),name,password,gender,DateUtil.parse(birthday,"yyyy-MM-dd"),
                education,address,hobby,likeType,avatar,motto);
        //

        ResultVO resultVO = userService.updateUser(user);

        ResultVO userList = userService.getUserList();
        request.setAttribute("resultVO", userList);
        HttpSession session = request.getSession();
        session.setAttribute("user", user);
        if (resultVO.getCode()==0){

            response.sendRedirect("UserServlet?method=toUpdatePage");
        }else {
            request.setAttribute("errTip", resultVO.getMsg());
            request.getRequestDispatcher("individual.jsp").forward(request, response);
        }
    }

    //UserServlet?method=logout
    protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("处理---->注销");
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        //3.让session立即失效
        session=null;
        response.sendRedirect("index.jsp");
    }

    //UserServlet?method=download
    protected void download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取下载的文件路径
        String fileUrl = request.getParameter("fileUrl");
        System.out.println("fileUrl = " + fileUrl);
        //2.fileUrl不为空
        if(StrUtil.isNotEmpty(fileUrl)){
            //3.获取文件名
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
            //4.获取下载文件的类型
            ServletContext application = this.getServletContext();
            String mimeType = application.getMimeType(fileName);
            System.out.println("mimeType = " + mimeType);
            //5.告诉客户端该文件不是直接解析 而是以附件形式打开(下载)
            response.addHeader("Content-Disposition",
                    "attachment;filename="
                            + URLEncoder.encode(fileName, "UTF-8"));
            //6.URL
            URL url=new URL(fileUrl);
            //7.打开一个流。字节输入流。读腾讯云上的图片
            URLConnection urlConnection = url.openConnection();
            InputStream is = urlConnection.getInputStream();
            //8.使用字节输出流，将文件的数据写给浏览器客户端
            ServletOutputStream os = response.getOutputStream();
            byte[] arr = new byte[1024];
            int len = -1;
            while( (len = is.read(arr)) !=-1){
                os.write(arr,0,len);
                os.flush();
            }
            os.close();
            is.close();
        }
    }

    //UserServlet?method=follow
    protected void follow(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->关注用户");
        String id = request.getParameter("id");
        User user = (User) request.getSession().getAttribute("user");
        Follow follow = new Follow(null, user.getId(), Integer.parseInt(id), new Date());
        ResultVO resultVO = followService.addFollow(follow);
        SendJSONUtil.send(resultVO,response);
    }

    //UserServlet?method=none
    protected void none(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("------------------------------->");
    }
}